package com.zmj.util;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;

import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.itextpdf.text.pdf.BaseFont;

public class GeneratePdfUtil {

    /**
     * html转pdf
     *
     * @throws Exception
     */
    public static void testHtml2Pdf(String htmlfilePath) {
        String str = "";
        try {
            String tempStr = "";

            FileInputStream is = new FileInputStream(htmlfilePath);//读取模块文件
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            while ((tempStr = br.readLine()) != null) {
                str = str + tempStr;
            }
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            //指定PDF的存放路径
            OutputStream os = new FileOutputStream("C:\\Users\\yangquan\\Desktop\\book\\index4.pdf");
            //OutputStream os = response.getOutputStream();
            ITextRenderer renderer = new ITextRenderer();
            ITextFontResolver fontResolver = renderer.getFontResolver();
            //指定字体。为了支持中文字体

            if ("linux".equals(getCurrentOperatingSystem())) {
                fontResolver.addFont("/usr/share/fonts/chiness/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            } else {
                fontResolver.addFont("G:\\simsun.ttc\\simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            }

            renderer.setDocumentFromString(str);
            // 解决图片的相对路径问题
            //renderer.getSharedContext().setBaseURL("src/main/resources/file");
            // renderer.getSharedContext().setBaseURL("file:\\C:\\Users\\yangquan\\Desktop\\book\\pdfOli\\static\\");
            renderer.layout();
            renderer.createPDF(os);
            renderer.finishPDF();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getCurrentOperatingSystem() {
        String os = System.getProperty("os.name").toLowerCase();
        System.out.println("---------当前操作系统是-----------" + os);
        return os;
    }

}
